package com.winai.launcher.service.heartBeat;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.util.Log;

import com.winai.launcher.service.ServiceHolder;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 当前进程服务
 *
 * @author sunfusheng on 2018/8/1.
 */
@SuppressLint("LongLogTag")
public abstract class AbsHeartBeatService extends Service {
    private static final String TAG = "---> AbsHeartBeatService";

    private Timer timer = new Timer();
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            onHeartBeat();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");
        onStartService();
        if (getHeartBeatMillis() > 0) {
            timer.schedule(timerTask, getDelayExecutedMillis(), getHeartBeatMillis());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand()");
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy()");
        onStopService();

        ServiceHolder.restartService(getApplicationContext(), ServiceHolder.mService);

        try {
            timer.cancel();
            timer.purge();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public abstract void onStartService();

    public abstract void onStopService();

    public abstract long getDelayExecutedMillis();

    public abstract long getHeartBeatMillis();

    public abstract void onHeartBeat();
}
